package com.itheima.dateutil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDateUtil {
    private MyDateUtil() {
    }

    //按照默认格式“yyyy-MM-dd HH:mm:ss”将日期对象格式化为字符串
    public static String dateToString(Date date) {
        return dateToString(date, null);
    }

    //按照指定模式将日期对象格式化为字符串
    public static String dateToString(Date date, String pattern) {
        if (pattern == null || "".equals(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String str = format.format(date);
        return str;
    }

    //按照指定的模式将字符串解析为日期对象
    public static Date stringToDate(String dateStr, String pattern) throws ParseException {
        if (pattern == null || "".equals(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = format.parse(dateStr);
        return date;
    }

    //按照默认模式"yyyy-MM-dd HH:mm:ss"将字符串解析为日期对象
    public static Date stringToDate(String dateStr) throws ParseException {
        return stringToDate(dateStr, null);
    }

    //日期区间毫秒值
    public static long millisecondBetween(Date date1, Date date2) throws ParseException{
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        return time2 > time1 ? time2-time1:time1-time2;
    }
    //日期区间年月日
    public static long daysBetween(Date date1, Date date2) throws ParseException{
       return millisecondBetween(date1,date2)/1000/60/60/24;
    }
}
